package com.ruoyi.camera.domain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.camera.service.ApiService;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class TokenManager {

    private static final Logger logger = LoggerFactory.getLogger(TokenManager.class);
    // 使用ConcurrentHashMap 来存储 token
    private final Map<String, String> tokenStore = new ConcurrentHashMap<>();
    private final ApiService apiService;
    @Autowired
    public TokenManager(ApiService apiService) {
        this.apiService = apiService;
    }
    /**
     * 获取 token。如果 token 已存在，则返回现有的 token；否则，调用 API 获取新 token。
     */
    public synchronized String getToken() {
        // 从缓存中获取 token
        String token = tokenStore.get("currentToken");
        if (token == null || token.isEmpty()) {
            // 如果没有找到有效的 token，则获取新 token
            try {
                Map<String, Object> response = apiService.getRawResponse();
                if (response != null && response.containsKey("resData")) {
                    Map<String, Object> resData = (Map<String, Object>) response.get("resData");
                    token = (String) resData.get("token");

                    if (token != null && !token.isEmpty()) {
                        // 存储新获取的 token
                        tokenStore.put("currentToken", token);
                        logger.info("获取新token: {}", token);
                    } else {
                        throw new RuntimeException("resData中找不到Token或为空");
                    }
                } else {
                    throw new RuntimeException("来自service的response格式无效");
                }
            } catch (Exception e) {
                logger.error("获取令牌失败: ", e);
                throw new RuntimeException("无法获取令牌", e);
            }
        }

        return token;
    }
    /**
     * 清除当前存储的 token，强制下一次请求重新获取。
     */
    public void clearToken() {
        tokenStore.remove("currentToken");
        logger.info("当前token已清除.");
    }
}
